<?php
class Cache {
	var $_path = "";

	function getInstance($path){           
		static $instance = null;      
		if(!$instance) {       
			$instance= new Cache($path);
		}

		return $instance;       
	}

	function Cache($path) {
		if(substr($path, -1) != "/") {
			$path .= "/";
		}
		
		$this->_path = $path;
	}
	
	function getStoreFile($key) {
		return $this->_path.$key.".php";
	}
	
	function add($key, $value, $lifetime = 0) {
		$filename = $this->getStoreFile($key);

		if($fp = @fopen($filename, 'w')) {
			$record = array();
			if($lifetime > 0) {
				$record["expire"] = date("Y-m-d H:i:s", time() + $lifetime);
			} else {
				$record["expire"] = "0000-00-00 00:00:00";
			}
			
			$record["data"] = serialize($value);
			
			$content = "<?php\n";
			$content.= "\$d".md5($key)."=".var_export($record, true).";\n";
			$content.= "?>";
			
			@fwrite($fp, $content);
			fclose($fp);

			chmod($filename, 0777);
		} else {
			return false;
		}

		return true;
	}

	function set($key, $value, $lifetime) {
		$this->add($key, $value, $lifetime);
	}

	function delete($key) {
		$filename = $this->getStoreFile($key);
		if(file_exists($filename)){
			unlink($filename);
		}
		
		return true;
	}

	function get($key) {
		$filename = $this->getStoreFile($key);

		if(file_exists($filename)){
			require($filename);
			
			$value = ${"d".md5($key)};
			
			if($value["expire"] != "0000-00-00 00:00:00" && strtotime($value["expire"]) < time()) {
				return false;
			}

			return unserialize($value["data"]);
		} else {
			return false;
		}
	}
}
?>